package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"gin-learn-notes/config"
	"gin-learn-notes/model"
	"gin-learn-notes/request"
	"gin-learn-notes/response"
	"gin-learn-notes/utils"
	"strings"
	"time"
)

func RegisterUser(req request.RegisterRequest) (*model.User, error) {
	user := &model.User{
		Name: req.Name,
		Age:  req.Age,
	}

	if err := config.DB.Create(user).Error; err != nil {
		return nil, err
	}

	return user, nil
}

func GetUserByID(id uint) (*model.User, error) {
	var user model.User
	if err := config.DB.Where("id = ?", id).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func UpdateUser(req request.UpdateUserRequest) error {
	var user model.User
	if err := config.DB.First(&user, req.ID).Error; err != nil {
		return err
	}
	if req.Name != "" {
		user.Name = req.Name
	}
	if req.Age != nil {
		user.Age = *req.Age
	}
	return config.DB.Save(&user).Error
}

func DeleteUser(id uint) error {
	var user model.User
	if err := config.DB.Where("id = ?", id).First(&user).Error; err != nil {
		return err
	}
	return config.DB.Delete(&user).Error
}

func GetUserList(req request.UserListRequest) ([]model.User, int64, error) {
	//var users []model.User
	//var total int64

	db := config.DB.Model(&model.User{})

	//if req.Page < 1 {
	//	req.Page = 1
	//}
	//if req.PageSize < 1 || req.PageSize > 100 {
	//	req.PageSize = 10
	//}

	req.Keyword = strings.TrimSpace(req.Keyword)
	//关键词搜索
	if req.Keyword != "" {
		db = db.Where("name LIKE ?", "%"+req.Keyword+"%")
	}

	//年龄筛选
	if req.MinAge > 0 {
		db = db.Where("age >= ?", req.MinAge)
	}
	if req.MaxAge > 0 {
		db = db.Where("age <= ?", req.MaxAge)
	}
	//查询总数
	//if err := db.Count(&total).Error; err != nil {
	//	return nil, 0, err
	//}
	// 分页查询
	//if err := db.Offset((req.Page - 1) * req.PageSize).
	//	Limit(req.PageSize).
	//	Find(&users).Error; err != nil {
	//	return nil, 0, err
	//}

	//return users, total, nil
	return utils.Paginate[model.User](db, req.Page, req.PageSize)
}

func GetUserProfileWithCache(userID uint) (*model.User, error) {
	cacheKey := fmt.Sprintf("user:%d", userID)

	//先查询缓存
	cacheStr, err := utils.RedisGet(cacheKey)
	if err == nil && cacheStr != "" {
		var user model.User
		// 缓存命中，返回缓存中的数据
		json.Unmarshal([]byte(cacheStr), &user)
		return &user, nil
	}

	//缓存未命中，查询数据库
	user, err := GetUserByID(userID)
	if err != nil {
		return nil, err
	}

	//将查询结果写入缓存，缓存设置为10分钟
	userStr, _ := json.Marshal(user)
	utils.RedisSet(cacheKey, string(userStr), 10*time.Minute)
	return user, nil
}

func DoLogin(username string, password string) (*response.LoginResult, error) {
	var user model.User
	if err := config.DB.Where("name = ? AND password = ?", username, password).First(&user).Error; err != nil {
		return nil, errors.New("用户名或密码错误")
	}

	token, err := utils.GenerateToken(user.ID)
	if err != nil {
		return nil, err
	}
	return &response.LoginResult{
		Token:    token,
		UserID:   user.ID,
		Username: user.Name,
	}, nil
}
